package com.ygqh.baby.config;

import com.ygqh.baby.redis.RedisDao;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisSentinelPool;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

    @Value("${spring.redis.password}")
    private String password;

    @Value("${spring.redis.pool.max-idle}")
    private int maxIdle;

    @Value("${spring.redis.pool.max-wait}")
    private long maxWait;

    @Value("${spring.redis.pool.min-idle}")
	private int minIdle;

    @Value("${spring.redis.pool.max-active}")
    private int maxActive;

    @Value("${spring.redis.pool.masterName}")
    private String masterName;

    @Value("${spring.redis.pool.sentinels}")
    private String sentinels;

    @Bean
    public RedisDao redisDao() {
        GenericObjectPoolConfig jedisPoolConfig = this.initPoolConfig();
        Set<String> set = new HashSet<>(Arrays.asList(sentinels.split(",")));
        JedisSentinelPool sentinelPool = new JedisSentinelPool(masterName, set, jedisPoolConfig, password);
        RedisDao redisDao = new RedisDao();
        redisDao.setJedisPool(sentinelPool);
        return redisDao;
    }

    private GenericObjectPoolConfig initPoolConfig() {
        GenericObjectPoolConfig jedisPoolConfig = new GenericObjectPoolConfig();
        // 控制一个pool最多有多少个可用的的jedis实例
        jedisPoolConfig.setMaxTotal(maxActive);
        // 最大能够保持空闲状态的对象数
        jedisPoolConfig.setMaxIdle(maxIdle);
        // 超时时间
        jedisPoolConfig.setMaxWaitMillis(maxWait);
        // 在borrow一个jedis实例时，是否提前进行validate操作；如果为true，则得到的jedis实例均是可用的；
        jedisPoolConfig.setTestOnBorrow(false);
        // 在还会给pool时，是否提前进行validate操作
        jedisPoolConfig.setTestOnReturn(false);
        return jedisPoolConfig;
    }
}
